package com.example.userservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.userservice.mapper.UserMapper;
import com.example.userservice.model.Result;
import com.example.userservice.model.User;
import com.example.userservice.model.dto.UserRegisterDTO;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * AI生成测试类
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class ShardingTestController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 批量注册用户测试分库分表
     */
    @PostMapping("/batch-register")
    public Result<Map<String, Object>> batchRegister(@RequestParam(defaultValue = "4") int count) {
        Map<String, Object> result = new HashMap<>();
        List<Long> userIds = new ArrayList<>();
        
        for (int i = 1; i <= count; i++) {
            UserRegisterDTO dto = new UserRegisterDTO();
            dto.setUsername("testuser" + System.currentTimeMillis() + "_" + i);
            dto.setPassword("123456");
            dto.setEmail("test" + System.currentTimeMillis() + "_" + i + "@example.com");
            dto.setPhone("1" + String.format("%010d", System.currentTimeMillis() % 10000000000L + i));
            
            try {
                Result<Void> registerResult = userService.register(dto);
                if (registerResult.getCode() == 1000) {
                    // 获取刚插入的用户ID
                    User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                            .eq(User::getUsername, dto.getUsername()));
                    if (user != null) {
                        userIds.add(user.getUserId());
                        log.info("用户注册成功: username={}, userId={}, 分片信息: db={}, table={}", 
                                dto.getUsername(), user.getUserId(), 
                                user.getUserId() % 2, user.getUserId() % 2);
                    }
                }
            } catch (Exception e) {
                log.error("注册用户失败: {}", dto.getUsername(), e);
            }
        }
        
        result.put("total", count);
        result.put("success", userIds.size());
        result.put("userIds", userIds);
        return Result.ok(result);
    }

    /**
     * 查询用户分布情况
     */
    @GetMapping("/distribution")
    public Result<Map<String, Object>> getUserDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 查询所有用户
        List<User> allUsers = userMapper.selectList(null);
        
        // 按分片统计
        Map<String, Long> dbDistribution = allUsers.stream()
                .collect(Collectors.groupingBy(
                        user -> "ds" + (user.getUserId() % 2),
                        Collectors.counting()
                ));
        
        Map<String, Long> tableDistribution = allUsers.stream()
                .collect(Collectors.groupingBy(
                        user -> "users_" + (user.getUserId() % 2),
                        Collectors.counting()
                ));
        
        result.put("totalUsers", allUsers.size());
        result.put("databaseDistribution", dbDistribution);
        result.put("tableDistribution", tableDistribution);
        result.put("userSamples", allUsers.stream().limit(10)
                .map(user -> Map.of(
                        "userId", user.getUserId(),
                        "username", user.getUsername(),
                        "targetDb", "ds" + (user.getUserId() % 2),
                        "targetTable", "users_" + (user.getUserId() % 2)
                )).collect(Collectors.toList()));
        
        return Result.ok(result);
    }

    /**
     * 根据用户ID查询（测试精确路由）
     */
    @GetMapping("/user/{userId}")
    public Result<User> getUserById(@PathVariable Long userId) {
        log.info("查询用户ID: {}, 预期路由到: ds{}.users_{}", userId, userId % 2, userId % 2);
        User user = userMapper.selectById(userId);
        return Result.ok(user);
    }
}